package com.qb.mobile.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.qb.mobile.R;
import com.qb.mobile.model.Phonebook;

/**
 * @author <a href="mailto:dangcongthanhtrung@gmail.com">dangtrung</a>
 * 
 * SystemPhonebookAdapter.java class
 *
 */
public class SystemPhonebookAdapter extends ArrayAdapter<Phonebook> {

	private Context context;
	private List<Phonebook> listPhonebook;

	public SystemPhonebookAdapter(Context context, 
			List<Phonebook> listPhonebook) {
		super(context, android.R.layout.simple_list_item_1, listPhonebook);
		this.context = context;
		this.listPhonebook = listPhonebook;
	}

	@Override
	public int getCount() {
		return ((null != listPhonebook) ? listPhonebook.size() : 0);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public Phonebook getItem(int position) {
		return ((null != listPhonebook) ? listPhonebook.get(position) : null);
	}

	public View getView(int position, View convertView, ViewGroup viewGroup) {

		Phonebook phonebook = listPhonebook.get(position);
		
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.system_phone_row, viewGroup, false);
		}
		
		TextView tvName = (TextView) convertView.findViewById(R.id.txtName);
		tvName.setText("Name : " + phonebook.getName());

		TextView tvPhone = (TextView) convertView
				.findViewById(R.id.txtPhoneHome);
		tvPhone.setText("Phone : " + phonebook.getPhones().get(0).getNumber());
		
		/*TextView tvAddress = (TextView) convertView.findViewById(R.id.txtAddress);
		tvAddress.setText("Address : asd sad sadsa das dsadsad");*/
		
		ImageView image = (ImageView) convertView.findViewById(R.id.image);
		image.setScaleType(ImageView.ScaleType.FIT_XY);
		if (phonebook.getPhoto() != null) {
			byte[] photoBlob = phonebook.getPhoto().getPhoto();
			Bitmap photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
			Drawable drawable = new BitmapDrawable(photoBitmap);
			image.setBackgroundDrawable(drawable);
		} else {
			image.setBackgroundResource(R.drawable.ic_contact_picture);
		}
		image.refreshDrawableState();
		image.requestFocus();
		
		ImageView imageNext = (ImageView) convertView.findViewById(R.id.imageNext);
		imageNext.setBackgroundResource(R.drawable.btn_next_default);
		convertView.setTag(phonebook);
		
		return convertView;

	}
}
